﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace SharePointManager
{
    public static class ErrorHandler
    {
        public static string GetFriendlyErrorMessage(string OriginalErrorMessage)
        {
            switch (OriginalErrorMessage)
            {
                case "":
                    return DefaultErrorMessage();
                default:
                    return ReturnFriendlyMessageByErrorCode(OriginalErrorMessage);
            }
        }
        private static string ReturnFriendlyMessageByErrorCode(string Message)
        {
            //Log the error in the event log
            LogErrorToEventLog(Message);
            //Example: 'The request failed with HTTP status 401: Unauthorized.'
            if (Message.Contains("401"))
                return "Access denied. You don't have enough permissions to perform this action.";
            if (Message.Contains("There is an error in XML document"))
                return "Unable to load list items. One of the items has an illegal character!";
            if (Message.Contains("Cannot open the requested Sharepoint Site"))
                return "Unable to process your request. \nError:Cannot open the requested Sharepoint Site";
            if (Message.Contains("CannotBeDeleted"))
                return "The field your are trying to delete is a system field and cannot be deleted";
            return DefaultErrorMessage();
        }
        private static string DefaultErrorMessage()
        {
            return "Unknown error!";
        }
        private static void LogErrorToEventLog(string ErrorMessage)
        {
            System.Diagnostics.EventLog.WriteEntry("SharePoint Handler", ErrorMessage, EventLogEntryType.Error, 100);
        }
    }
}
